# -*- coding: utf-8 -*-
"""
@Time ： 2024/4/10 19:21
@Auth ： 李天天
"""
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS
from Common.handle_log import do_log
from Common.connect_to_device import *

class InfluxDBHandler:
    def __init__(self, url=None, token=None, org=None):
        if not url:
            url = "http://10.10.118.92:8086"
        if not token:
            token = "z7TVAZCoJY6T9bA1adSArAbddRqjhVOpGL1OD-ihe1ErnU4mYCknalpS0mXUa6U_D_w3kpqLvoXZsZutboy7MQ=="
        if not org:
            org = "perf"
        self.client = InfluxDBClient(url=url, token=token, org=org)
        self.write_api = self.client.write_api(write_options=SYNCHRONOUS)
        self.bucket = bucket_name

    def write_data(self, measurement, tags, fields):
        point = Point(measurement).tag(**tags).field(**fields)
        self.write_api.write(self.bucket, self.client.org, point)

    def write_mul_data(self, measurements):
        try:
            self.write_api.write(self.bucket, self.client.org, measurements)
            do_log.info(f"{bucket_name}数据写入")
            return True

        except Exception as e:
            do_log.info(f"写入数据时出错: {e}")
            return False

    def query_data(self, query):
        result = self.client.query_api().query(query, org=self.client.org)
        return list(result)

    def close_connection(self):
        self.client.close()
